package baseFx.serialization.json.jackson;

import baseFx.common.utils.EnumUtils;
import baseFx.serialization.json.EnumFormat;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.BeanProperty;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.ser.ContextualSerializer;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

public class EnumSerializer extends JsonSerializer<Enum> implements ContextualSerializer {
    private EnumFormat fmt;

    @Override
    public void serialize(Enum anEnum, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (fmt == null) {
            Integer id = EnumUtils.getId(anEnum);
            if (id != null) {
                jsonGenerator.writeNumber(id);
            } else {
                jsonGenerator.writeString(anEnum.name());
            }
        } else {
            Integer id = null;
            String name = "";
            if (fmt.showId()) {
                id = EnumUtils.getId(anEnum);
            }
            if (fmt.useToString()) {
                name = anEnum.toString();
            } else if (fmt.showName()) {
                name = anEnum.name();
            }
            if (id != null && name.length() > 0) {
                Map<String, Object> map = new HashMap<>(2);
                map.put("id", id);
                map.put("name", name);
                jsonGenerator.writeObject(map);
            } else if (id != null) {
                jsonGenerator.writeNumber(id);
            } else if (name.length() > 0) {
                jsonGenerator.writeString(name);
            } else {
                jsonGenerator.writeNull();
            }
        }
    }

    @Override
    public JsonSerializer<?> createContextual(SerializerProvider serializerProvider, BeanProperty beanProperty) {
        if (beanProperty != null) {
            if (beanProperty.getType().isEnumType()) {
                EnumFormat attr = beanProperty.getAnnotation(EnumFormat.class);
                if (attr != null) {
                    EnumSerializer serializer = new EnumSerializer();
                    serializer.fmt = attr;
                    return serializer;
                }
            }
        }
        return this;
    }
}
